<template>
    <div class="complaint-list">
        <div class="filter-container">
            <!-- 现有的筛选组件 -->
            <el-button class="filter-item" style="float: right;" type="danger" @click="handleLogout">
                退出登录
            </el-button>
            <el-select v-model="filters.brandName" placeholder="请选择车辆品牌" style="width: 200px;" class="filter-item" clearable>
                <el-option
                    v-for="brand in brandList"
                    :key="brand.id"
                    :label="brand.name"
                    :value="brand.name">
                </el-option>
            </el-select>
            <el-input v-model="filters.problem" placeholder="请输入投诉问题" style="width: 200px;" class="filter-item" />
            <el-input v-model="filters.carType" placeholder="请输入车型" style="width: 200px;" class="filter-item" />
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus"
                @click="handleCreate">
                添加投诉
            </el-button>
        </div>

        <el-table :data="list" style="width: 100%" v-loading="listLoading">
            <el-table-column prop="id" label="投诉编号" width="80" />
            <el-table-column prop="brandName" label="投诉品牌" width="120" />
            <el-table-column prop="problem" label="投诉问题" />
            <el-table-column prop="carType" label="投诉车型" width="120" />
            <el-table-column prop="complaintsTime" label="投诉时间" width="120" />
            <el-table-column prop="status" label="状态" width="100">
                <template slot-scope="{row}">
                    <el-tag :type="row.status === '0' ? 'warning' : 'success'">
                        {{ row.status === '0' ? '信息审核' : '厂家受理' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
                <template slot-scope="{row}">
                    <el-button size="mini" type="primary" @click="handleUpdateStatus(row)"
                        :disabled="row.status !== '0'">
                        编辑
                    </el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total" />
        </div>
    </div>
</template>

<script>
export default {
    name: 'ComplaintList',
    data() {
        return {
            list: [],
            total: 0,
            listLoading: true,
            currentPage: 1,
            pageSize: 5,
            brandList: [], // 添加品牌列表数据
            filters: {
                brandName: '',
                problem: '',
                carType: ''
            }
        }
    },
    created() {
        this.getBrandList() // 添加获取品牌列表的调用
        this.getList()
    },
    methods: {
        // 添加获取品牌列表的方法
        async getBrandList() {
            try {
                const response = await this.$axios({
                    method: 'get',
                    url: '/car/api/brands',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                })
                if (response.data.code === 0) {
                    this.brandList = response.data.data
                }
            } catch (error) {
                console.error('获取品牌列表失败:', error)
                this.$message.error('获取品牌列表失败')
            }
        },
        handleFilter() {
            this.currentPage = 1
            this.searchList()
        },

        async searchList() {
            this.listLoading = true
            try {
                const token = localStorage.getItem('token');
                const response = await this.$axios({
                    method: 'get',
                    url: '/car/api/selectByName',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    params: {
                        brandName: this.filters.brandName,
                        problem: this.filters.problem,
                        carType: this.filters.carType,
                        current: this.currentPage,
                        size: this.pageSize
                    }
                })
                if (response.data.code === 0) {
                    this.list = response.data.data.records || []
                    this.total = response.data.data.total || 0
                } else {
                    this.$message.error(response.data.msg || '搜索失败')
                }
            } catch (error) {
                console.error('搜索失败:', error)
                this.$message.error('搜索失败')
            } finally {
                this.listLoading = false
            }
        },

        // 修改原有的 getList 方法，当搜索条件都为空时使用
        async getList() {
            if (this.filters.brandName || this.filters.problem || this.filters.carType) {
                return this.searchList()
            }
            this.listLoading = true
            try {
                const token = localStorage.getItem('token');
                const response = await this.$axios({
                    method: 'get',
                    url: '/car/api/page',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    params: {
                        pageNo: this.currentPage,
                        pageSize: this.pageSize
                    }
                })
                if (response.data.code === 0) {
                    // Ensure list is an array
                    this.list = response.data.data.records || []
                    // Get total from the pagination data
                    this.total = response.data.data.total || 0
                } else {
                    this.$message.error(response.data.msg || '获取数据失败')
                }
            } catch (error) {
                console.error('获取投诉列表失败:', error)
                this.$message.error('获取投诉列表失败')
            } finally {
                this.listLoading = false
            }
        },
        handleUpdateStatus(row) {
            this.$confirm('确认将此投诉标记为已处理?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const response = await this.$axios({
                        method: 'put',
                        url: `/car/api/update/status/${row.id}`, // 修改请求路径
                        headers: {
                            'Authorization': `Bearer ${localStorage.getItem('token')}`
                        }
                    });
                    
                    if (response.data.code === 0) {
                        this.$message.success('状态更新成功');
                        this.getList();
                    } else {
                        this.$message.error(response.data.msg || '状态更新失败');
                    }
                } catch (error) {
                    console.error('状态更新失败:', error);
                    this.$message.error('状态更新失败');
                }
            }).catch(() => {});
        },

        // 处理每页显示数量变化
        handleSizeChange(val) {
            this.pageSize = val;
            this.getList();
        },

        // 处理页码变化
        handleCurrentChange(val) {
            this.currentPage = val;
            this.getList();
        },

        // 添加创建投诉方法
        handleCreate() {
            this.$router.push('/complaint/create');
        },

        async handleLogout() {
            try {
                const response = await this.$axios({
                    method: 'post',
                    url: '/car/logout',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (response.data.code === 0) {
                    localStorage.removeItem('token');
                    this.$message.success('退出登录成功');
                    this.$router.push('/login');
                } else {
                    this.$message.error(response.data.msg || '退出登录失败');
                }
            } catch (error) {
                console.error('退出登录失败:', error);
                this.$message.error('退出登录失败');
                // 即使请求失败，也清除token并跳转
                localStorage.removeItem('token');
                this.$router.push('/login');
            }
        },
        async handleDelete(row) {
            try {
                await this.$confirm('确认删除该投诉记录?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
                
                const response = await this.$axios({
                    method: 'delete',
                    url: `/car/api/delete/${row.id}`,
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (response.data.code === 0) {
                    this.$message.success('删除成功');
                    this.getList(); // 刷新列表
                } else {
                    this.$message.error(response.data.msg || '删除失败');
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除失败:', error);
                    this.$message.error('删除失败');
                }
            }
        }
    }
}
</script>

<style scoped>
.complaint-list {
    padding: 20px;
}

.filter-container {
    padding-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.filter-item {
    margin-right: 10px;
    margin-bottom: 10px;
}

.pagination-container {
    margin-top: 30px;
    text-align: center;
}
</style>